/**
 * 
 */
package edu.arizona.bio5.onto.decomposition.persistent.rdf;

import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.semanticweb.owlapi.model.OWLEntity;

import edu.arizona.bio5.onto.decomposition.Atom;
import edu.arizona.bio5.onto.decomposition.SignatureLabel;
import edu.arizona.bio5.onto.decomposition.persistent.ADPersistenceException;
import edu.arizona.bio5.onto.decomposition.persistent.LabelPersister;

/**
 * @author pklinov
 *
 */
public class SesameSignatureLabelPersister extends SesameAbstractPersister implements LabelPersister {

	SesameSignatureLabelPersister(RepositoryConnection conn) {
		super(conn);
	}

	public void persist(Atom atom) throws ADPersistenceException {
		SignatureLabel sigLabel = (SignatureLabel) atom.getLabel(SignatureLabel.TYPE);
		
		if (sigLabel == null || sigLabel.getSignature().isEmpty()) {
			return;
		}
		
		ValueFactory factory = getValueFactory();
		RepositoryConnection conn = getConnection();
		URI hasLabel = factory.createURI(RDFADConstants.AD_ATOM_HAS_LABEL);
		URI labelInstance = factory.createURI(RDFADConstants.AD_LABEL_INSTANCE + "_" + SignatureLabel.TYPE + "_" + atom.getID().toString());
		URI labelType = factory.createURI(RDFADConstants.AD_SIGNATURE_LABEL);
		URI hasSignature = factory.createURI(RDFADConstants.AD_LABEL_HAS_SIGNATURE);
		URI hasTerm = factory.createURI(RDFADConstants.AD_SIGNATURE_HAS_TERM);
		
		try {
			conn.add(SesameOWLRDFUtils.getAtomURI(atom, factory), hasLabel, labelInstance, getNamedGraph());
			conn.add(labelInstance, RDF.TYPE, labelType, getNamedGraph());
			//need to generate URI for the signature
			URI sigNode = factory.createURI(RDFADConstants.AD_SIGNATURE_INSTANCE + "_" + SignatureLabel.TYPE + "_" + atom.getID().toString());

			conn.add(labelInstance, hasSignature, sigNode, getNamedGraph());
			//now serialize the signature
			for (OWLEntity term : sigLabel.getSignature()) {
				URI termURI = factory.createURI(term.getIRI().toString());
				
				conn.add(sigNode, hasTerm, termURI, getNamedGraph());
			}
		} catch (RepositoryException e) {
			throw new ADPersistenceException(e);
		}
	}

}
